package com.hhc.netty;

import android.util.Log;

import com.example.administrator.smartdevice.serial.SerialPortManager;
import com.example.administrator.smartdevice.utils.AgentSharedPreferences;
import com.example.administrator.smartdevice.utils.AppApplication;

import java.util.List;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * Created by huhaichao on 2018/3/5.
 */

public class NettyClientHandler extends SimpleChannelInboundHandler<NettyBaseMsg> {
    private static final String TAG = "hhc";
    private int send_count = 0;
    private int receive_count = 0;

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            switch (e.state()) {
                case WRITER_IDLE:
                    NettyPingMsg nettyPingMsg = new NettyPingMsg();
                    nettyPingMsg.setType(NettyMsgType.DEVICE);
                    nettyPingMsg.setDeviceId(AgentSharedPreferences.getMemberInfo(AppApplication.getContext()).getMemberDeviceId());
                    ctx.writeAndFlush(nettyPingMsg);
                    Log.e("心跳包", "send心跳包" + (send_count++));
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 收到数据时
     */
    @Override
    protected void messageReceived(ChannelHandlerContext ctx, NettyBaseMsg msg) throws Exception {
        if (msg != null) {
            switch (msg.getNettyMsgType()) {
                case PING:
                    Log.e("心跳包", "device-receive心跳包" + (receive_count++));
                    break;
                case OPERATION:
                    Log.e(TAG, "=========控制设备=========");
                    NettyOperationMsg nettyOperationMsg = (NettyOperationMsg) msg;
                    List<DeviceModel> operationList = nettyOperationMsg.getList();
                    for (int i = 0; i < operationList.size(); i++) {
                        Log.d(TAG, "控制applianceId= " + operationList.get(i).getApplianceId());
                        Log.d(TAG, "控制applianceType= " + operationList.get(i).getApplianceType());
                        Log.d(TAG, "控制status=" + operationList.get(i).getStatus());
                        //10:电灯 20：门锁： 30：窗帘 50：空调 40：电视
                        //10：开 20：关
//                        String applianceType = null;
//                        if ("12345601".equals(operationList.get(i).getApplianceId())) {
//                            applianceType = "10";
//                        } else if ("12345602".equals(operationList.get(i).getApplianceId())) {
//                            applianceType = "20";
//                        } else if ("12345603".equals(operationList.get(i).getApplianceId())) {
//                            applianceType = "30";
//                        } else if ("12345604".equals(operationList.get(i).getApplianceId())) {
//                            applianceType = "40";
//                        } else if ("12345605".equals(operationList.get(i).getApplianceId())) {
//                            applianceType = "50";
//                        }
//                        SerialPortManager.getInstance().contrlHard(applianceType, operationList.get(i).getStatus());
                        SerialPortManager.getInstance().sendData("30", operationList.get(i).getApplianceId(), operationList.get(i).getApplianceType(), operationList.get(i).getStatus(), "111111");
                    }
                    Log.e(TAG, "=========控制设备=========");
                    break;
                case ASK_STATUS:
                    NettyAskStatusMsg nettyAskStatusMsg = (NettyAskStatusMsg) msg;
                    List<DeviceModel> list = nettyAskStatusMsg.getList();
                    list = NettyClient.getInstance().getDeviceStatus(list);
//                    List<DeviceModel> main_list = NettyClient.getInstance().getDeviceList();
//                    for (int i = 0; i < list.size(); i++) {
//                        Log.d(TAG, "请求的设备deviceId=" + list.get(i).getDeviceId());
//                        Log.d(TAG, "请求的设备applianceId=" + list.get(i).getApplianceId());
//                        for (int j = 0; j < main_list.size(); j++) {
//                            Log.d(TAG, "在线设备deviceId=" + main_list.get(i).getDeviceId());
//                            Log.d(TAG, "在线设备applianceId=" + main_list.get(i).getApplianceId());
//                            if (list.get(i).getDeviceId().equals(main_list.get(j).getDeviceId()) &&
//                                    list.get(i).getApplianceId().equals(main_list.get(j).getApplianceId())) {
//                                list.get(i).setOnlineStatus(main_list.get(j).getOnlineStatus());
//                                list.get(i).setStatus(main_list.get(j).getStatus());
//                            }
//                        }
//                    }
                    NettyReplyStatusMsg nettyReplyStatusMsg = new NettyReplyStatusMsg();
                    nettyReplyStatusMsg.setClientId(nettyAskStatusMsg.getClientId());
                    nettyReplyStatusMsg.setDeviceId(nettyAskStatusMsg.getDeviceId());
                    nettyReplyStatusMsg.setList(list);
                    //发送
                    NettyClient.getInstance().sendMessage(nettyReplyStatusMsg);
                    break;
                case REPLY_STATUS:
                    //移动控制端（有）
                    //收到：家电状态
//                    EventBus.getDefault().post(msg);
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 建立连接成功时执行一次
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        Log.e(TAG, "channelActive: 连接成功");
        NettyClient.getInstance().setConnectState(NettyClient.CONNECTED);
        //上线信息
        NettyOnlineMsg nettyOnlineMsg = new NettyOnlineMsg();
        nettyOnlineMsg.setNettyMsgType(NettyMsgType.ONLINE);
        //设置上线类型(和终端区别)
        nettyOnlineMsg.setType(NettyMsgType.DEVICE);
        nettyOnlineMsg.setDeviceId(AgentSharedPreferences.getMemberInfo(AppApplication.getContext()).getMemberDeviceId());
        ctx.writeAndFlush(nettyOnlineMsg);
    }

    /**
     * 连接断开时
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        NettyClient.getInstance().setConnectState(NettyClient.DISCONNECTION);
        Log.e(TAG, "连接已断开,正在重新连接...");
        NettyClient.getInstance().doConnect();
    }
}
